<template>
  <div>
    <el-button type="primary" round @click="addCategory"> 添加分类 </el-button>

    <!-- 分类数据 -->
    <!-- <el-tree
        :data="tableData"
        :props="defaultProps"
        @node-click="handleNodeClick"
      ></el-tree> -->

    <el-table :data="tableData" style="width: 100%" border>
      <el-table-column label="id" width="150">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span style="margin-left: 10px">{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="分类名称" width="150">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span style="margin-left: 10px">{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="等级" width="150">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span style="margin-left: 10px">{{ scope.row.gradeId }}</span>
        </template>
      </el-table-column>

      <el-table-column label="父级" width="150">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span
            v-for="parent in sumData"
            :key="parent.id"
            style="margin-left: 10px"
          >
            <span v-if="parent.id == scope.row.parentCategoryId">
              {{ parent.name }}
            </span>
          </span>
        </template>
      </el-table-column>

      <el-table-column label="是否有效" width="150">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span style="margin-left: 10px">{{ scope.row.isActived }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEditCategory(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="block">
      <el-pagination
        :current-page="pager.currentPage"
        :page-size="pager.pageSize"
        layout="prev, pager, next, jumper,sizes, total"
        :total="pager.totalSize"
        :page-sizes="[5, 10, 15, 20]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>

    <!-- Dialog模态框 -->
    <el-dialog title="操作" :visible.sync="dialogFormVisible">
      <el-form
        :model="formdata"
        ref="numberValidateForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item
          label="分类名称"
          prop="name"
          :rules="[{ required: true, message: '分类名称不能为空' }]"
        >
          <el-input
            type="text"
            v-model="formdata.name"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item
          v-if="!isHidden"
          label="选择父级分类:"
          label-width="150px"
        >
          <el-cascader
            v-model="formdata.parentName"
            :options="options"
            :props="{ checkStrictly: true }"
            clearable
          >
          </el-cascader>
        </el-form-item>

        <div>
          <el-button @click="handleCancel">取 消</el-button>
          <el-button @click="resetForm('numberValidateForm')">重置</el-button>
          <el-button type="primary" @click="handleSave">确 定</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>
 
 

<script>
import {
  getlistCategories,
  addCommodityCategory,
  updateCommodityCategory,
  delCommodityCategory,
} from "../api/categories";
export default {
  data() {
    return {
      //  是否隐藏
      isHidden: false,

      numberValidateForm: {
        name: "",
      },

      sumData: [],

      //获取初始化分类的数据
      tableData: [],

      pager: {
        //每页显示条目个数
        pageSize: 5,
        currentPage: 1,
        totalSize: 0,
      },

      dialogFormVisible: false,
      formdata: {
        id: 0,
        name: "",
        parentName: "",
      },  

      // 初始化索引，用于修改
      curIndex: 0,
      value: [],
      options: [],
    };
  },
  methods: {
    // 重置按钮
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },

    //添加分类时
    addCategory() {
      this.dialogFormVisible = true;
      (this.isHidden = false), (this.formdata.name = "");
      this.formdata.parentName = "";

      (this.options = []),
        this.sumData.map((x) => {
          let currentGrade = {
            id: 0,
            parentId: 0,
            value: "",
            label: "",
            children: [],
          };

          // 判断是不是最高级;
          if (x.parentCategoryId == 0) {
            currentGrade.id = x.id;
            currentGrade.value = x.name;
            currentGrade.label = x.name;

            // Object.assign方法用于对象的合并，
            // 将router添加到{}  并赋给obj对象中
            let obj = Object.assign({}, currentGrade);

            this.options.push(obj);
          }

          // 遍历所有的父级组件
          this.options.map((child) => {
            //如果父级组件的id等于当前组件的父级id
            if (child.id == x.parentCategoryId) {
              let children = {
                id: 0,
                parentId: 0,
                value: "",
                label: "",
                // children: [],
              };

              children.id = x.id;
              children.parentId = x.parentCategoryId;
              children.value = x.name;
              children.label = x.name;

              //将子分类装到父级分类的children中
              let obj = Object.assign({}, children);

              child.children.push(obj);
            }

            //遍历第三级
            // child.children.map((childThree) => {
            //   // console.log(childThree.parentId);
            //   // console.log(child.id);

            //   if (childThree.id == x.parentCategoryId) {
            //     // 将第三级加入到当前级别的children中
            //     console.log(x);

            //     let children = {
            //       id: 0,
            //       parentId: 0,
            //       value: "",
            //       label: "",
            //       children: [],
            //       disabled: true,
            //     };

            //     children.id = x.id;
            //     children.parentId = x.parentCategoryId;
            //     children.value = x.name;
            //     children.label = x.name;

            //     //将子分类装到父级分类的children中
            //     let obj = Object.assign({}, children);

            //     childThree.children.push(obj);
            //   }
            // });
          });
        });

      console.log(this.options);
    },

    //编辑分类时
    handleEditCategory(index, row) {
      this.isHidden = true;
      this.dialogFormVisible = true;
      this.formdata.id = row.id;
      this.formdata.name = row.name;
      this.curIndex = index;
    },

    //  删除分类按钮
    handleDelete(index, row) {
      console.log(index);
      console.log(row);

      //通过row.id找到当前的id
      this.$confirm("确定要删除该分类嘛?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delCommodityCategory(row.id).then(({ data }) => {
            console.log(data);
            this.tableData.splice(index, 1);
            this.pager.totalSize -= 1;
            let nun = parseInt(this.pager.totalSize / this.pager.pageSize) + 1;
            if (
              //判断取余后为零 pager.pageindex-1
              parseInt(this.pager.totalSize % this.pager.pageSize) === 0 &&
              this.pager.currentPage === nun
            ) {
              this.pager.currentPage -= 1;
            }
            //重新拉取
            this.fetchData();
          });
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // handleNodeClick(data) {
    //   console.log(data);
    // },

    //拉取数据
    fetchData() {
      let params = {
        pager: this.pager,
      };

      //获取所有分类
      getlistCategories(params.pager)
        .then((res) => {
          var resful = res.data;

          console.log(resful);
          this.tableData = resful.currentData;
          this.pager = resful.pager;
          this.sumData = resful.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },

    // 通过页码来拉取数据
    handleCurrentChange(val) {
      this.pager.currentPage = val;
      this.fetchData();
    },

    // 改变页大小来拉取数据
    handleSizeChange(val) {
      this.pager.pageSize = val;
      this.fetchData();
    },

    // 取消按钮
    handleCancel() {
      this.dialogFormVisible = false;
    },
    // 确定按钮
    handleSave() {
      this.dialogFormVisible = false;

      //将获取到的最后一个分类赋给formdata.parentName
      this.formdata.parentName =
        this.formdata.parentName[this.formdata.parentName.length - 1];

      if (this.formdata.id === 0) {
        if (this.formdata.name == "") {
          this.$message({
            message: "分类名称不可为空",
             type: 'warning'
          });
        } else {
          //添加分类接口
          addCommodityCategory(this.formdata)
            .then((res) => {
              console.log(res);
              this.tableData.push(res.data);
              this.$message({
                message: "添加分类成功",
                type: "success",
              });

              this.fetchData();
            })
            .catch((err) => {
              console.log(err);
            });
        }
      } else {
        //修改分类名
        updateCommodityCategory(this.formdata.id, this.formdata)
          .then((res) => {
            console.log(res);
            this.tableData.splice(this.curIndex, 1, res.data);

            this.$message({
              message: "修改分类成功",
              type: "success",
            });

            this.fetchData();
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
  },

  mounted() {
    this.fetchData();
  },
};
</script>

<style>
</style>